package com.qf.grabtickets.service.impl;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.canstants.Constants;
import com.qf.entity.Coupon;
import com.qf.entity.User;
import com.qf.entity.UserCou;

import com.qf.grabtickets.mapper.TUserCouMapper;
import com.qf.grabtickets.service.ITUserCouService;
import com.qf.vo.ResultVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ljc
 * @since 2023-03-10
 */
@Service
public class TUserCouServiceImpl extends ServiceImpl<TUserCouMapper, UserCou> implements ITUserCouService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResultVo grabTickets(String token, User user) throws Exception {
        boolean validate = JWT.of(token).setKey(Constants.SECRET.getBytes()).validate(0);
        if (!validate) {
            throw new Exception("第一轮已经抢过票啦");
        }
        Integer id1 = Integer.valueOf(JWT.of(token).getPayload("sub").toString());

        if (!user.getId().equals(id1)) {
            throw new Exception("请勿刷抢票");
        }

        Coupon coupon = null;
        try {
            coupon = (Coupon) redisTemplate.opsForSet().pop(Constants.REDIS_COUPON_KEY);


        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.ok("请下次参与");
        }
        UserCou userCou = new UserCou();
        if (coupon == null) {
            throw new Exception("没抢到,请下次再抢");
        }
        userCou.setCid(coupon.getId());
        userCou.setUid(user.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("user",user);
        map.put("userCou",userCou);
        map.put("tickets",coupon);

        rabbitTemplate.convertAndSend(Constants.EXCHANGE_NAME, null ,map);
        return ResultVo.ok("抢票成功");
    }
}
